package com.itheima.health.job;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;

@Component
public class SortSetmealJob {

    @Reference
    private SetmealService setmealService;

    @Autowired
    private JedisPool jedisPool;

    public void sortAndOvertime(){
        List<Setmeal> list = setmealService.findAll();
        Jedis jedis = jedisPool.getResource();

        //遍历list，将所有套餐存入setmealRanking
        list.forEach(setmeal -> {

            Double setmealExist = jedis.zscore("setmealRanking", JSON.toJSONString(setmeal));
            if (null == setmealExist){
                jedis.zadd("setmealRanking",0,JSON.toJSONString(setmeal));
            }
        });

        //将套餐按分值从大到小排序并存入redis的setmealList
        Set<String> setmealRanking = jedis.zrevrange("setmealRanking", 0, -1);
        List<Setmeal> listRanking = new ArrayList<>();
        setmealRanking.forEach(s -> {
            listRanking.add(JSON.parseObject(s,Setmeal.class));
        });
        jedis.set("setmealList",JSON.toJSONString(listRanking));

        //将分值前三的semealDetail在redis中的有效时长延长三天
        setmealRanking = jedis.zrevrange("setmealRanking", 0, 2);
        setmealRanking.forEach(s -> {
            Setmeal setmeal = JSON.parseObject(s, Setmeal.class);
            String setmealId = "setmealDetail_"+setmeal.getId();
            jedis.setex(setmealId,new Random().nextInt(7200) + 3600*24*3,JSON.toJSONString(setmeal));
        });
        jedis.close();
    }
}
